package odgs.pda;

import java.io.IOException;
import java.net.Socket;

import odgs.Connection;
import odgs.message.Message;
import odgs.pda.sender.SendMessageHandler;

public class PdaConnection extends Connection {

	protected PdaMessageReceiver receiver;

	public PdaConnection(Socket socket) {
		try {
			receiver = new PdaMessageReceiver(this, socket.getInputStream());
			new Thread(receiver).start();

			this.socket = socket;

			os = socket.getOutputStream();
			is = socket.getInputStream();
			ip = socket.getInetAddress().getHostAddress();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void sendMessage(Message msg) {
		SendMessageHandler sender = getSender(msg);
		sender.send(msg, os);
		System.out.println();
		System.out.println(msg.getName());
		System.out.println();
	}
	
	public SendMessageHandler getSender(Message msg) {
		String path = "pda.sender." + msg.getName() + "Sender";
		Class clazz;
		try {
			clazz = Class.forName(path);
			return (SendMessageHandler) clazz.newInstance();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return null;
	}
}